#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
迁移脚本 - 将xhs_collection-master项目迁移到小红书数据管理系统中
"""

import os
import sys
import shutil
from pathlib import Path
import logging

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler()
    ]
)
logger = logging.getLogger('xhs_migrate')

def migrate_crawler():
    """
    将xhs_collection-master项目迁移到小红书数据管理/xhs_crawler目录下
    """
    # 获取当前脚本所在目录
    current_dir = Path(os.path.dirname(os.path.abspath(__file__)))
    parent_dir = current_dir.parent
    
    # 源目录和目标目录
    source_dir = parent_dir / "xhs_collection-master"
    target_dir = current_dir / "xhs_crawler"
    
    logger.info(f"源目录: {source_dir}")
    logger.info(f"目标目录: {target_dir}")
    
    # 检查源目录是否存在
    if not source_dir.exists():
        logger.error(f"源目录不存在: {source_dir}")
        return False
    
    # 创建目标目录（如果不存在）
    if not target_dir.exists():
        logger.info(f"创建目标目录: {target_dir}")
        target_dir.mkdir(parents=True)
    
    try:
        # 复制所有文件和目录
        for item in source_dir.glob('*'):
            # 目标路径
            target_path = target_dir / item.name
            
            if item.is_dir():
                # 如果是目录，递归复制
                logger.info(f"复制目录: {item.name}")
                if target_path.exists():
                    shutil.rmtree(target_path)
                shutil.copytree(item, target_path)
            else:
                # 如果是文件，直接复制
                logger.info(f"复制文件: {item.name}")
                shutil.copy2(item, target_path)
        
        logger.info("迁移完成！")
        return True
    
    except Exception as e:
        logger.error(f"迁移过程中发生错误: {str(e)}")
        return False

def update_crawler_bridge():
    """
    更新爬虫桥接模块，使其指向新的爬虫目录
    """
    bridge_file = Path(os.path.dirname(os.path.abspath(__file__))) / "xhs_crawler_bridge.py"
    
    if not bridge_file.exists():
        logger.error(f"爬虫桥接文件不存在: {bridge_file}")
        return False
    
    try:
        # 读取文件内容
        with open(bridge_file, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 更新爬虫模块路径
        new_content = content.replace(
            'CRAWLER_MODULE_PATH = os.path.join(PARENT_DIR, "xhs_collection-master", "xhs_crawler_gradio.py")',
            'CRAWLER_MODULE_PATH = os.path.join(CURRENT_DIR, "xhs_crawler", "xhs_crawler_gradio.py")'
        )
        
        # 写入更新后的内容
        with open(bridge_file, 'w', encoding='utf-8') as f:
            f.write(new_content)
        
        logger.info("爬虫桥接模块已更新！")
        return True
    
    except Exception as e:
        logger.error(f"更新爬虫桥接模块时发生错误: {str(e)}")
        return False

if __name__ == "__main__":
    logger.info("开始迁移xhs_collection-master项目...")
    
    # 迁移爬虫项目
    if migrate_crawler():
        # 更新爬虫桥接模块
        update_crawler_bridge()
        logger.info("迁移完成！")
    else:
        logger.error("迁移失败！") 